import { VALIDATE_FAILED, getRefPromise, validateFormAndTables, validateFormModelAndTables } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { httpAction, getAction } from '@/api/manage'
import { queryMaterialVoInfoById } from '@/api/erp/commonapi'
import { handleValueChange, handleJvxeValueChange } from '@/utils/erputils/erpcommonutils';
import { validateDuplicateValue, getNowFormatDate } from '@/utils/util'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { create } from 'tinymce';
export const JVxeTableModelMixin = {
  data() {
    return {
      title: '操作',
      visible: false,
      confirmLoading: false,
      searchMaterialCode: '',
      scrolling: true,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
  },
  watch: {
    $router: function (to, from) {
      let fromparams = from.params;
      let toparams = to.params;
      console.log("fromparams" + JSON.stringify(fromparams));
      if (fromparams != toparams) {
        created();
      }
    }
  },
  async created() {
    if (!this.model.id) {
      //this.model.billdate=getNowFormatDate();
      let currentuser = this.$store.getters.userInfo
      this.model.companyid = localStorage.getItem(currentuser.id + '_list_companyid');
    }

    let routeparams = this.$route.params;
    if (routeparams != undefined && (routeparams.id != '' && routeparams.id != undefined)) {
      let params = { id: routeparams.id }
      //获取主表信息
      await this.getMainData(this.url.querybyId || this.url.queryById, params);

      if (this.refKeys != null && this.refKeys.length > 0) {
        for (let i = 0; i < this.refKeys.length; i++) {
          let subtable = this.refKeys[i];
          let subtablename = this.refKeys[i] + "Table";
          //获取分录信息
          this.requestSubTableData(this.url[subtable].list, params, this[subtablename])
          if (routeparams.disableSubmit != null && routeparams.disableSubmit != undefined) {
            this.disabled = routeparams.disableSubmit
            this.auditvisable = false;
          } else {
            this.disabled = true;
            this.auditvisable = true;
            this.audittaskid = routeparams.taskId;
          }
        }
      }
    }

    let params1 = {
      objectcode: this.maincusObject,
    }

    let res = await getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params1);
    if (res.success) {
      let cusret = res.result;
      this.maincusList = cusret;
      for (let i = 0; i < cusret.length; i++) {
        if (this.model.id) {
          //不是新增，则进行赋值
          this.$set(this.maincusItems, cusret[i]["customcode"], this.model[cusret[i]["customcode"]])
        } else {
          this.$set(this.maincusItems, cusret[i]["customcode"], "");
        }
      }

      console.log("get the mainmodelifno....--->" + JSON.stringify(this.maincusItems));
    }
    //获取分录自定义字段
    let itemParams = {
      objectcode: this.itemcusObject,
    }
    this.requestTableCustomCode("/base/scmcustomfields/getcustomfieldsbyobjectcode", itemParams, this.itemTable);

  },
  methods: {
    async insertMaterialCode(event,materialtype) {
      // console.log(event);
      let keyevent = event.$event;
      if (keyevent) {
        if (keyevent.keyCode === 13) {
          //结束
          console.log(event.value);
          let materialcode = event.value;
          //获取物料信息，新增行到当前页面上
          let itemKey = this.refKeys[0];

          let materialinfo = await queryMaterialVoInfoById({ materialid: materialcode });
          if (materialinfo.success) {
            let mat = materialinfo.result;
            if (mat) {
              let uomid=''
              let curItemTable = this.$refs[itemKey];
              let columns  = curItemTable.columns;
              for(let j = 0; j< columns.length; j++){
                if(columns[j].key === 'materialid'){
                  let props = columns[j].props;
                  if(props.hasOwnProperty("materialtype")){
                    let curMaterialType = props.materialtype;
                    if(curMaterialType == '0'){
                      //采购
                      uomid = mat.pouomid
                    }else if(curMaterialType == '1'){
                      uomid = mat.saleuomid
                    }else if(curMaterialType == '2'){
                      uomid = mat.stockuomid
                    }
                  }
                  break;
                }
              }
              let rows = {
                materialid: mat.id,
                materialcode: mat.materialcode,
                materialname: mat.materialname,
                qty: 1,
                uomid: uomid,
                model: mat.model,
                specs: mat.mspecs,
                taxinprice: mat.saleprice,
                taxrate: mat.taxrate,
              }
              let tableData = curItemTable.getAll().tableData;
              if (tableData.length == 0) {
                curItemTable.addRows(rows, false);
                this.searchMaterialCode = '';
                // curItemTable.dataSource = curItemTable.getAll().tableData;
                return;
              }
              let isHave = false;
              for (let i = 0; i < tableData.length; i++) {
                let curMat = tableData[i];
                if (curMat.materialid == mat.id) {
                  isHave = true;
                  let newQty = curMat.qty + 1;
                  this.$set(curMat, 'qty', newQty);
                  this.$set(curMat,'taxinvalue',parseFloat(curMat.taxinprice) * newQty );
                }
              }
              if (isHave === false) {
                curItemTable.addRows(rows, false);
              } else {
                curItemTable.loadData(tableData)
                curItemTable.handleTableData()
                curItemTable.updateFooter()
                curItemTable.updateCache()
                curItemTable.checkSelectionStatus()
              }
            }
          }

          this.searchMaterialCode = '';
        }
      }

    },
    handleValueChange(event) {
      handleJvxeValueChange(event)
    },
    getMainData(url, params) {
      getAction(url, params).then((res) => {
        if (res.success) {
          if (res.result instanceof Array) {
            this.model = res.result[0];
          } else {
            this.model = res.result;
          }
          // this.model=res.result || res.result[0]
        }
      })
    },

    /** 获取所有的JVxeTable实例 */
    getAllTable() {
      if (!(this.refKeys instanceof Array)) {
        throw this.throwNotArray('refKeys')
      }
      let values = this.refKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    /** 遍历所有的JVxeTable实例 */
    eachAllTable(callback) {
      // 开始遍历
      this.getAllTable().then(tables => {
        console.log("tables", tables)
        tables.forEach((item, index) => {
          if (typeof callback === 'function') {
            callback(item, index)
          }
        })
      })
    },

    /** 当点击新增按钮时调用此方法 */
    add() {
      if (typeof this.addBefore === 'function') this.addBefore()
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
      }
      this.eachAllTable((item) => {
        //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        setTimeout(() => {
          item.addRows()
        }, 30)
        //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
      })
      if (typeof this.addAfter === 'function') this.addAfter(this.model)

      let params = {
        objectcode: this.maincusObject,
      }
      getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params).then(res => {
        if (res.success) {
          let cusret = res.result;
          this.maincusList = cusret;
          for (let i = 0; i < cusret.length; i++) {
            this.$set(this.maincusItems, cusret[i]["customcode"], "");
          }

          console.log("get the mainmodelifno....--->" + JSON.stringify(this.maincusItems));
        }
      })
      //获取分录自定义字段
      let itemParams = {
        objectcode: this.itemcusObject,
      }
      this.requestTableCustomCode("/base/scmcustomfields/getcustomfieldsbyobjectcode", itemParams, this.itemTable);



      this.edit(this.model)
    },
    /**
     * 获取分录自定义字段的信息
     * @param {*} url 
     * @param {*} params 
     * @param {*} tab 
     */
    requestTableCustomCode(url, params, tab) {
      if (tab) {
        tab.loading = true
        //获取自定义的格式信息
        let customformaturl = "/base/scmcustomformat/getcolumnlist";
        getAction(customformaturl, params).then(res => {
          if (res.success) {
            const cusret = res.result;
            console.log("columns:" + JSON.stringify(cusret));
            let newColumns = [];
            for (let i = 0; i < cusret.length; i++) {
              let currentitemtype = cusret[i]

              let newColumn = {
                title: currentitemtype.colname,
                key: currentitemtype.colid,
                width: currentitemtype.colwidth,
                placeholder: '请输入${title}',
                defaultValue: '',
              }
              if (currentitemtype.colvisable === 'false') {
                this.$set(newColumn, "type", FormTypes.hidden);
                newColumns.push(newColumn);
                continue
              }

              if (currentitemtype.onlyread === 'true') {
                this.$set(newColumn, 'disabled', "true")
              }
              if (currentitemtype.formtype === 'sel_material') {
                this.$set(newColumn, 'type', FormTypes.sel_material);
              } else if (currentitemtype.formtype === 'input') {
                this.$set(newColumn, 'type', FormTypes.input);
              } else if (currentitemtype.formtype === 'input_number') {
                this.$set(newColumn, 'type', FormTypes.inputNumber)
              } else if (currentitemtype.formtype === 'date') {
                this.$set(newColumn, 'type', FormTypes.date)
              } else if (currentitemtype.formtype === 'sel_vendor') {
                this.$set(newColumn, 'type', FormTypes.sel_vendor)
              } else if (currentitemtype.formtype === 'search') {
                this.$set(newColumn, 'type', FormTypes.sel_search)
                this.$set(newColumn, 'dictCode', currentitemtype.coldict)
              }
              newColumns.push(newColumn);
            }

            tab.columns = newColumns;

          }
          tab.loading = false;
        })
        getAction(url, params).then(res => {
          const cusret = res.result;
          let origcolumn = tab.columns;
          if (cusret) {
            for (let i = 0; i < cusret.length; i++) {
              let curItem = cusret[i];
              let newColumn = {
                title: curItem.customname,
                key: curItem.customcode,
                type: FormTypes.input,
                width: "100px",
                placeholder: '请输入${title}',
                defaultValue: '',
              }
              var result = origcolumn.some(item => {
                if (item.key === curItem.customcode) {
                  return true
                }
              })
              if (!result) {
                origcolumn.push(newColumn);
              }
            }
          }
          tab.columns = [...origcolumn];
          // tab.setColumns(origcolumn);
        }).finally(() => {
          tab.loading = false
        })
      }
    },
    /** 当点击了编辑（修改）按钮时调用此方法 */
    edit(record) {
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.$refs.form.resetFields()
      // this.model = Object.assign({}, record)
      if (record.hasOwnProperty("id")) {
        this.getMainData(this.url.querybyId || this.url.queryById, { id: record.id });
        this.model.id = record.id;
      } else {
        this.model = Object.assign({}, record)
      }
      if (this.model.companyid === null || this.model.companyid === undefined ||
        this.model.companyid === '') {
        let currentuser = this.$store.getters.userInfo
        this.model.companyid = localStorage.getItem(currentuser.id + '_list_companyid');
      }
      //增加对自定义字段的处理
      let params = {
        objectcode: this.maincusObject,
      }
      getAction("/base/scmcustomfields/getcustomfieldsbyobjectcode", params).then(res => {
        if (res.success) {
          let cusret = res.result;
          this.maincusList = cusret;
          for (let i = 0; i < cusret.length; i++) {
            this.$set(this.maincusItems, cusret[i]["customcode"], record[cusret[i]["customcode"]]);
          }
        }
      })

      //获取分录自定义字段
      let itemParams = {
        objectcode: this.itemcusObject,
      }
      this.requestTableCustomCode("/base/scmcustomfields/getcustomfieldsbyobjectcode", itemParams, this.itemTable);

      let subtable = this.refKeys[0];
      let subtablename = this.refKeys[0] + "Table";

      let params1 = { id: record.id }

      //获取分录信息
      this.requestSubTableData(this.url[subtable].list, params1, this[subtablename])

      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    /** 关闭弹窗，并将所有JVxeTable实例回归到初始状态 */
    close() {
      this.visible = false
      this.eachAllTable((item) => {
        item._remove()
      })
      this.$emit('close')
    },

    /** 查询某个tab的数据 */
    requestSubTableData(url, params, tab, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        let { result } = res
        let dataSource = []
        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        tab.dataSource = dataSource
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        tab.loading = false
      })
    },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    request(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      console.log("formData===>", formData);
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.formDisabled = true;
          this.$emit('ok')
          if (typeof this.afterSave === 'function') {
            this.afterSave(formData);
          }

          // this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },

    /* --- handle 事件 --- */

    /** ATab 选项卡切换事件 */
    handleChangeTabs(key) {
      // 自动重置scrollTop状态，防止出现白屏
      getRefPromise(this, key).then(vxeTable => {
        vxeTable.resetScrollTop()
      })
    },
    /** 关闭按钮点击事件 */
    handleCancel() {
      this.close()
    },
    /** 确定按钮点击事件 */
    handleOk() {
      /** 触发表单验证 */
      // console.log("getAlltable():"+JSON.stringify(this.getAllTable()));

      
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form, this.model, tables)
      }).then(allValues => {
        /** 一次性验证一对一的所有子表 */
        return this.validateSubForm(allValues)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }

        if (allValues.tablesValue.length > 0) {
          let tabledata = allValues.tablesValue[0].tableData;
          if (tabledata.length > 0) {
            tabledata.forEach(item => {
              if (item.hasOwnProperty("id")) {
                if (item.id.indexOf("row_") != -1) {
                  delete item.id;
                }
              }
            })
          }
        }


        let formData = this.classifyIntoFormData(allValues)
        if (this.maincusItems != null && this.maincusItems != undefined) {
          const newformData = Object.assign(this.maincusItems, formData);
          return this.request(newformData)
        } else {
          return this.request(formData);
        }
      }).catch(e => {
        if (e.error === VALIDATE_FAILED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    },
    //校验所有子表表单
    validateSubForm(allValues) {
      return new Promise((resolve) => {
        resolve(allValues)
      })
    },
    /* --- throw --- */

    /** not a function */
    throwNotFunction(name) {
      return `${name} 未定义或不是一个函数`
    },

    /** not a array */
    throwNotArray(name) {
      return `${name} 未定义或不是一个数组`
    }

  }
}